package com.java.controller;

import java.util.Arrays;
import java.util.Map;

import cn.hutool.crypto.digest.BCrypt;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.java.common.constant.UserConstant;
import com.java.common.exception.BusinessExceptionEnum;
import com.java.common.utils.CookieUtils;
import com.java.common.utils.JsonUtils;
import com.java.pojo.Users;
import com.java.pojo.bo.UserBo;
import com.java.service.UsersService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.java.common.utils.PageUtils;
import com.java.common.utils.R;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;


/**
 * 用户表
 *
 * @author jl
 * @since 2020-10-13 11:31:41
 */
@Api(tags = "用户管理")
@RestController
@RequestMapping("/passport")
public class UsersController {
    @Autowired
    private UsersService usersService;

    /**
     * 用户登出
     */
    @ApiOperation("用户登出")
    @PostMapping("/logout")
    public R logout(@RequestParam String userId, HttpServletRequest request, HttpServletResponse response) {

        CookieUtils.deleteCookie(request,response, UserConstant.USER_COOKIE_NAME);
        // todo 分布式会话中需要清除用户数据

        return R.ok();
    }

    /**
     * 用户登录
     */
    @ApiOperation("用户登录")
    @PostMapping("/login")
    public R login(@RequestBody @Valid UserBo userBo, HttpServletRequest request, HttpServletResponse response) {
        Users users = usersService.getOne(new LambdaQueryWrapper<Users>().eq(Users::getUsername, userBo.getUsername()));
        if (users == null) {
            return R.error(BusinessExceptionEnum.LOGIN_USER_ERROR.getDesc());
        }
        boolean checkpw = BCrypt.checkpw(userBo.getPassword(), users.getPassword());
        if (!checkpw) {
            return R.error(BusinessExceptionEnum.LOGIN_USER_ERROR.getDesc());
        }
        setNullProperty(users);
        // isEncode是否URLEncoder编码加密
        CookieUtils.setCookie(request,response,UserConstant.USER_COOKIE_NAME, JsonUtils.objectToJson(users),true);
        return R.ok(users);
    }

    /**
     * 查询用户名是否存在
     */
    @ApiOperation("查询用户名是否存在")
    @GetMapping("/usernameIsExist")
    public R usernameIsExist(@RequestParam String username) {
        Boolean isExist = usersService.queryUsernameIsExist(username);
        return isExist ? R.error(BusinessExceptionEnum.USER_LOGIN_NAME_EXIST.getDesc()) : R.ok();
    }

    /**
     * 用户注册
     */
    @ApiOperation("用户注册")
    @PostMapping("/regist")
    public R regist(@RequestBody @Valid UserBo userBo, HttpServletRequest request, HttpServletResponse response) {
        Boolean isExist = usersService.queryUsernameIsExist(userBo.getUsername());
        if (isExist) {
            return R.error(BusinessExceptionEnum.USER_LOGIN_NAME_EXIST.getDesc());
        }
        if (!userBo.getPassword().equals(userBo.getConfirmPassword())) {
            return R.error(BusinessExceptionEnum.CONFIRM_PASSWORD_NOT_MATCH.getDesc());
        }
        Users users = usersService.createUser(userBo);
        setNullProperty(users);
        // isEncode是否URLEncoder编码加密
        CookieUtils.setCookie(request,response,"user", JsonUtils.objectToJson(users),true);
        return R.ok();
    }

    /**
     * 带条件分页查询用户表
     */
    @ApiOperation("带条件分页查询用户表")
    @GetMapping("/list")
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = usersService.queryPage(params);

        return R.ok(page);
    }


    /**
     * 根据主键查询用户表
     */
    @ApiOperation("根据主键查询用户表")
    @GetMapping("/info/{id}")
    public R info(@PathVariable("id") String id) {
        Users users = usersService.getById(id);

        return R.ok(users);
    }

    /**
     * 新增用户表
     */
    @ApiOperation("新增用户表")
    @PostMapping("/save")
    public R save(@RequestBody Users users) {
        usersService.save(users);

        return R.ok();
    }

    /**
     * 修改用户表
     */
    @ApiOperation("修改用户表")
    @PutMapping("/update")
    public R update(@RequestBody Users users) {
        usersService.updateById(users);

        return R.ok();
    }

    /**
     * 删除用户表
     */
    @ApiOperation("删除用户表")
    @DeleteMapping("/delete")
    public R delete(@RequestBody String[] ids) {
        usersService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

    private void setNullProperty(Users users) {
        users.setPassword(null);
        users.setMobile(null);
        users.setEmail(null);
        users.setBirthday(null);
        users.setRealname(null);
        users.setCreatedTime(null);
        users.setUpdatedTime(null);
    }

}
